package cn.saltice.idempotence.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

/**
 * @program: idempotence
 * @description: tomcat配置文件
 * @author: Mr.Liu
 * @create: 2020-10-10 23:13
 **/
@Slf4j
@Component
public class TomcatConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    /**
     *
     * 修改 tomcat连接方式bio为nio的方式
     * 但是现在tomcat默认就是nio了，在TomcatServletWebServerFactory类中可以看到
     * 这个也可以在tomcat配置文件中修改连接器上面的protocol为org.apache.coyote.http11.Http11Nio2Protocol
     * 当然也有一中，Tomcat apr也是在Tomcat上运行高并发应用的首选模式，这个暂不搞
     * @param factory
     */
    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        ((TomcatServletWebServerFactory)factory).setProtocol("org.apache.coyote.http11.Http11Nio2Protocol");
        ((TomcatServletWebServerFactory)factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
            @Override
            public void customize(Connector connector) {
                org.apache.coyote.ProtocolHandler protocol = connector.getProtocolHandler();
                log.info("Tomcat({})  -- MaxConnection:{};MaxThreads:{};MinSpareThreads:{}",
                        protocol.getClass().getName(),
                        ((AbstractHttp11Protocol<?>) protocol).getMaxConnections(),
                        ((AbstractHttp11Protocol<?>) protocol).getMaxThreads(),
                        ((AbstractHttp11Protocol<?>) protocol).getMinSpareThreads());

            }
        });
    }
}
